<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="空地名称" prop="name">
            <el-input style="width: 120px" v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="土地所有权" label-width="120">
            <el-select placeholder="请选择" style="width: 120px" v-model="queryParams.ownership">
              <el-option v-for="item in LAND_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleActive">启用</el-button>
            <el-button type="primary" plain @click="handleForbidden">禁用</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                更多
                <el-icon class="el-icon--right"><arrow-down /></el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- <el-dropdown-item icon="Download" @click="importTemplate">下载模板</el-dropdown-item> -->
                  <!-- 注意 由于el-dropdown-item标签是延迟加载的 所以v-has-permi自定义标签不生效 需要使用v-if调用方法执行 -->
                  <!-- <el-dropdown-item icon="Top" @click="handleImport">导入数据</el-dropdown-item> -->
                  <el-dropdown-item icon="Download" @click="handleExport">导出数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="farmList" @selection-change="handleSelectionChange" @cell-dblclick="cellDbClick">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="主键" align="center" prop="id" />
        <el-table-column label="空地编码" align="center" width="140" prop="code"> </el-table-column>
        <el-table-column label="空地名称" align="center" prop="name" width="120" />
        <el-table-column label="土地所有权" align="center" prop="ownership" width="120" :formatter="formatOwnership" />
        <el-table-column label="电子围栏编码" align="center" prop="eFenceCode" width="160" />
        <el-table-column label="空地介绍" align="center" prop="introduction">
          <template #default="scope">
            <div v-html="scope.row.introduction"></div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" :formatter="formatStatus" width="140" />
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Leave" lang="ts">
import { listSpace, handleSpaceStatus } from '@/api/farm/index';
import { SpaceQuery, SpaceForm, SpaceVO, StatusForm } from '@/api/farm/types';
import { LAND_OPTIONS } from '@/constants/options';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const farmList = ref<SpaceVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const codes = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<SpaceForm, SpaceQuery>>({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10
  },
  rules: {}
});

const { queryParams } = toRefs(data);

const formatOwnership = (row, column, cellValue, index) => {
  let selType = LAND_OPTIONS.filter((item) => item.value === row.ownership);

  return selType.length > 0 ? selType[0].label : '';
};
const formatStatus = (row, column, cellValue, index) => {
  return row.status ? '启用' : '禁用';
};
/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSpace(queryParams.value);
  const { data } = res;
  farmList.value = data.records;

  total.value = data.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNo = 1;
  queryParams.value.name = undefined;
  queryParams.value.term = undefined;
  queryParams.value.ownership = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SpaceVO[]) => {
  ids.value = selection.map((item) => item.id);
  codes.value = selection.map((item) => item.code);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$router.push({
    path: `/farm/space/edit`,
    query: {
      type: 'add'
    }
  });
};
//双击进行修改
const cellDbClick = (row, column, cell, event) => {
  handleUpdate(row);
};

/** 修改按钮操作 */
const handleUpdate = (row?: SpaceVO) => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/farm/space/edit`,
    query: {
      id: row.id,
      type: 'update'
    }
  });
};

/** 查看按钮操作 */
const handleView = (row?: SpaceVO) => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/farm/space/edit`,
    query: {
      id: row.id,
      type: 'view'
    }
  });
};

/** 启用操作 */
const handleActive = async (row?: SpaceVO) => {
  const _ids = row?.id || ids.value;
  const _codes = row?.code || codes.value;
  if (ids.value.length == 0) {
    proxy?.$modal.msgError('请先选数据');
    return false;
  }

  await proxy?.$modal.confirm('是否确认启用为"' + _codes + '"的数据项？').finally(() => (loading.value = false));

  await handleSpaceStatus(_ids, true);
  proxy?.$modal.msgSuccess('启用成功');
  await getList();
};
/** 禁用用操作 */
const handleForbidden = async (row?: SpaceVO) => {
  const _ids = row?.id || ids.value;
  const _codes = row?.code || codes.value;
  if (ids.value.length == 0) {
    proxy?.$modal.msgError('请先选数据');
    return false;
  }

  await proxy?.$modal.confirm('是否确认禁用为"' + _codes + '"的数据项？').finally(() => (loading.value = false));

  await handleSpaceStatus(_ids, false);
  proxy?.$modal.msgSuccess('禁用成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'base/vacant/land/export',
    {
      ...queryParams.value
    },
    `space_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
